import 'dart:collection';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../app_main.dart';

/// 通用用户列表项样式
/// 姓名昵称 权限 电话      **添加·未激活（时间）
/// 部门/项目/城市         分类/编号
class CommonListItemWidget extends StatelessWidget {
  //上传头像
  final String putpicurl;

  //头像
  final String napicurl;

  //部门
  final String department;

  //项目
  final String projectname;

  //城市
  final String city;

  //姓名
  final String name;

  //分类
  final String groupName;

  //昵称
  final String nick;

  //权限
  final String roleid;

  //未激活
  final bool isAlive;

  //添加人
  final String uname;

  //上次打卡时间
  final int lastPunchTime;

  //编号
  final String number;

  //手机
  final String phone;

  //选择模式
  final bool selectMode;

  final String classname;

  const CommonListItemWidget(
      {Key key,
      this.putpicurl,
      this.napicurl,
      this.department,
      this.classname,
      this.name,
      this.groupName,
      this.nick,
      this.roleid,
      this.isAlive,
      this.uname,
      this.lastPunchTime,
      this.number,
      this.phone,
      this.projectname,
      this.city,
      this.selectMode = false})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      child: _toMainRowWidget(context),
      // color: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _toMainRowWidget(BuildContext context) {
    return Row(
      children: <Widget>[
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Container(
            width: 36,
            height: 36,
            child: VgCacheNetWorkImage(
              showOriginEmptyStr(putpicurl) ??
                  showOriginEmptyStr(napicurl ?? "") ??
                  '',
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
              defaultErrorType: ImageErrorType.head,
              defaultPlaceType: ImagePlaceType.head,
            ),
          ),
        ),
        SizedBox(
          width: 10,
        ),
        Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: (VgStringUtils.checkAllEmpty([
              department?.trim(),
              // projectname?.trim(),
              // city?.trim(),
              classname?.trim(),
              // itemBean?.coursename?.trim(),
            ]))
                ? MainAxisAlignment.center
                : MainAxisAlignment.spaceBetween,
            children: <Widget>[
              //姓名
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  CommonNameAndNickWidget(
                    name: name,
                    nick: nick,
                  ),
                  VgLabelUtils.getRoleLabel(roleid) ?? Container(),
                  _toPhoneWidget(),
                ],
              ),
              //部门/项目/城市
              _infoWidget(context)
            ],
          ),
        ),
        Expanded(
          child: selectMode ? _selectBtn() : _toColumnWidget(),
        ),
      ],
    );
  }

  Widget _toPhoneWidget() {
    return Offstage(
      offstage: phone == null || phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  /// 部门/项目/城市
  _infoWidget(BuildContext context) {
    List<String> textsList = List();
    String textStr = '';
    if (StringUtils.isNotEmpty(department)) {
      textsList.add(department);
    }
    if (StringUtils.isNotEmpty(classname)) {
      textsList.add(_classsStr());
    }
    // if (StringUtils.isNotEmpty(projectname)) {
    //   textsList.add(projectname);
    // }
    // if (StringUtils.isNotEmpty(city)) {
    //   textsList.add(city);
    // }
    if (textsList.length > 0) {
      textStr = textsList.join("/");
    } else {
      textStr = null;
    }

    if (textStr == null) {
      return SizedBox(
        height: 0,
      );
    }
    return Container(
      constraints: BoxConstraints(maxWidth: ScreenUtils.screenW(context)/2),
      child: Text(
        textStr,
        overflow: TextOverflow.ellipsis,
        maxLines: 1,
        style: TextStyle(
            color: textsList.length > 0 ? Color(0xff5e687c) : Color(0xfff95355),
            fontSize: 12,height: 1.2),
      ),
    );
  }

  /// 李珊珊添加·未激活 /打卡时间
  /// 分类名称·编号
  _toColumnWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        //未激活的
        Container(height: 16,
          alignment:Alignment.bottomRight,child:
        isAlive ?? true
            ? Text(VgDateTimeUtils.getFormatTimeStr(lastPunchTime) ?? '未打卡',
            style: TextStyle(fontSize: 10, color: VgColors.INPUT_BG_COLOR))
            : RichTextWidget(fontSize:10,contentMap: LinkedHashMap.from({StringUtils.isEmpty(uname) ? '' : '$uname添加·':VgColors.INPUT_BG_COLOR,
          '未激活':ThemeRepository.getInstance().getMinorRedColor_F95355() }),),)
        //激活的显示上次打卡时间
        ,

        //分类名称·编号
        Text(
          _getGroupAndIdStr(groupName, number),
          style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR),
          overflow: TextOverflow.ellipsis,
        )
      ],
    );
  }

  String _classsStr(){
    List<String> classListStr;
    String classStr = classname?.trim();
    if(classname != null){
      classListStr = classname?.trim()?.split(",");
      if(classListStr?.length!=0){
        if(classListStr?.length > 1){
          classStr = _classStrSubstring(classListStr[0],classListStr[0]?.length,classListStr?.length);
        }else if(classListStr?.length == 1){
          classStr = classListStr[0];
        }
      }
    }
    return classStr;
  }
  String _classStrSubstring(String str,int length,int classListLength){
    if(length > 7){
      return (str?.substring(0,7)+"...") + "等${classListLength }个班级";
    }else{
      return str + "等${classListLength}个班级";
    }
  }

  ///分类名称·编号
  String _getGroupAndIdStr(String groupName, String number) {
    if (StringUtils.isEmpty(groupName) && StringUtils.isEmpty(number)) {
      return '';
    }
    if (StringUtils.isNotEmpty(groupName) && StringUtils.isEmpty(number)) {
      return groupName;
    }
    if (StringUtils.isEmpty(groupName) && StringUtils.isNotEmpty(number)) {
      return number;
    }
    return groupName + "·" + number;
  }

  ///选择
  _selectBtn() {
    return Stack(
      children: <Widget>[
        Align(
          alignment: Alignment.centerRight,
          child: Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(12)),
                border: Border.all(
                    color: ThemeRepository.getInstance().getLineColor_3A3F50(),
                    width: 0.5)),
            child: Text(
              '选择',
              style: TextStyle(
                  color:
                      ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                  fontSize: 13),
            ),
            height: 24,
            width: 50,
          ),
        )
      ],
    );
  }
}
